package com.bgi.cg.oss4j.provider.upyun;

import com.upyun.RestManager;
import com.upyun.UpException;
import com.upyun.UpYunUtils;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Author Z.cg
 * @Date 2023/9/14
 * @Version 1.0
 **/
public class RestManagerExt extends RestManager {
    private OkHttpClient mClient;

    /**
     * 初始化 UpYun 存储接口
     *
     * @param bucketName 空间名称
     * @param userName   操作员名称
     * @param password   密码，不需要MD5加密
     * @return UpYun object
     */
    public RestManagerExt(String bucketName, String userName, String password) {
        super(bucketName, userName, password);
        this.mClient = new OkHttpClient.Builder().connectTimeout(getTimeout(), TimeUnit.SECONDS).readTimeout(getTimeout(), TimeUnit.SECONDS).writeTimeout(getTimeout(), TimeUnit.SECONDS).build();
    }


    public Response writeFile(String bucket, String filePath, File file, Map<String, String> params) throws IOException, UpException {
        return request("PUT", bucket, filePath, RequestBody.create(null, file), params);
    }

    public Response deleteFile(String bucket, String filePath, Map<String, String> params) throws IOException, UpException {
        return request("DELETE", bucket, filePath, null, params);
    }

    private Response request(String method, String bucket, String filePath, RequestBody body, Map<String, String> params) throws UpException, IOException {
        String date = UpYunUtils.getGMTDate();
        // 获取链接
        String url = getApiDomain() + UpYunUtils.formatPath(bucket, filePath);
        String sign = UpYunUtils.sign(method, date, HttpUrl.get(url).encodedPath(), userName, password, params == null ? null : params.get(PARAMS.CONTENT_MD5.getValue()));
        Request.Builder builder = new Request.Builder().url(url).header("Date", date).header("Authorization", sign).header("User-Agent", UpYunUtils.VERSION).method(method, body);
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.header(entry.getKey(), entry.getValue());
            }
        }
        return this.mClient.newCall(builder.build()).execute();
    }
}
